package com.zzk.www.tool.common;

import com.zzk.www.domain.User;
import com.zzk.www.domain.UserVo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Created by zzk on 2017/12/18.
 */
public class SerializeUtil {

    private static final Log log = LogFactory.getLog(SerializeUtil.class);

    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            // 序列化
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;
        if (bytes == null) {
            return null;
        }
        try {
            // 反序列化
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }


    public static void main(String[] args) {


        UserVo user = new UserVo();
        user.setUserId("1");
        user.setPassword("zzk");
        user.setUserName("zzk");

        byte[] result = SerializeUtil.serialize(user);
        System.out.println(result);


    }



}
